/**
 * Created by Jason_PC on 2017/8/3.
 */
define(['app/client', 'swiper', 'jquery.barrager'], function (w) {

    (function ($) {
        $.getUrlParam = function (name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r !== null) {
                return decodeURIComponent(r[2]);
            }
            return null;
        };
    })(jQuery);

    var page = {
        gifts: [],
        emojis: [],
        giftBox: [],
        userLevels: [],
        sendGiftInfo: [],
        hideDanmu: false,
        timeout: function () {
            // 刷新送礼物时间
            $(page.sendGiftInfo).each(function (i, item) {
                if (item.time > 0) {
                    item.time--;
                }

                //超时重新统计发送数量
                if (item.time <= 0) {
                    item.count = 0;
                }
            });

            //统计礼物显示隐藏
            $(page.giftBox).each(function (i, item) {
                item.time -= 1;
                if (item.time <= 0) {
                    $('[data-giftId="' + item.domId + '"]').addClass('giftLeave');
                } else {
                    $('[data-giftId="' + item.domId + '"]').removeClass('giftLeave');
                }
                if (item.time < 0) {
                    $('[data-giftId="' + item.domId + '"]').remove();
                    page.giftBox.splice($.inArray(item, page.giftBox), 1);
                }
            });
        },
        userInfo: null,
        getGift: function (_id) {
            var arr = $.grep(page.gifts, function (item) {
                return _id === item._id;
            });
            if (arr.length > 0) {
                return arr[0];
            }
            return null;
        },
        getEmoji: function (name) {
            var arr = $.grep(this.emojis, function (item) {
                return name === item.name;
            });
            if (arr.length > 0) {
                return arr[0];
            }
            return null;
        },
        getLevel: function (level) {
            var arr = $.grep(page.userLevels, function (item) {
                return level === item.level;
            });
            if (arr.length > 0) {
                return arr[0];
            }
            return null;
        },
        randerEmojiContent: function (contents) {
            var pattern1 = /\[\:[\u4e00-\u9fa5\0-9]+\]/g;
            var pattern2 = /\[\:[\u4e00-\u9fa5\0-9]+\]/;
            var content = contents.match(pattern1);
            if (content == null) {
                return contents;
            }
            var str = contents;
            for (i = 0; i < content.length; i++) {
                for (j = 0; j < page.emojis.length; j++) {
                    if (page.emojis[j].name === content[i]) {
                        var src = page.emojis[j].gif;
                        var img = '<img class="chat-phiz" alt="" src="' + src + '">';
                        str = str.replace(content[i], img);
                        break;
                    }
                }
            }
            return str;
        },
        // 渲染礼物 如果是combo的需要延长显示时间
        randerGift: function (giftinfo) {
            // 第一步 判断是否是需要加成显示的礼物
            var exists = $.grep(page.giftBox, function (item) {
                if (item._id === giftinfo._id && item.user_id === giftinfo.user_id) {
                    item.count = giftinfo.count;
                    if (item.time < 3) {
                        item.time += 3;
                    }
                    $('[data-giftId="' + item.domId + '" ]').prependTo($('.room-chat-tips'));
                }
                return item._id === giftinfo._id && item.user_id === giftinfo.user_id;

            });

            if (exists.length === 0) {
                // 第二步 显示礼物并添加

                //礼物domid
                var domId = 'gid_' + (new Date()).getTime();
                var showInfo = {
                    time: 3,
                    domId: domId
                };
                $.extend(showInfo, giftinfo);
                page.giftBox.push(showInfo);
                console.log(showInfo);
                var dom = '  <div class="room-gift-animtaion-item" data-giftId="' + domId + '"'
                    + ' style="left: 0px; opacity: 1;">'
                    + '<div class="gift-img">'
                    + '<img src="' + giftinfo.img.icon + '">'
                    + '</div>'
                    + '<div class="gift-info">'
                    + '<span class="from-name">' + giftinfo.fromName + '</span>'
                    + '<span class="gift-name">赠送给主播 ' + giftinfo.name + ' </span>'
                    + '</div>'
                    + '<div class="gift-combo">'
                    + '<span class="combo-symbol icon-x"> X </span>'
                    + '<div class="gift-combo-hit">' + giftinfo.count + '</div>'
                    + '</div>'
                    + ' </div>';
                $('.room-chat-tips').prepend(dom);

            } else {
                $('.room-chat-tips [data-giftId="' + exists[0].domId + '"] .gift-combo-hit').text(giftinfo.count);
            }


        },
        ChangeH: function () {
            var viewContainerH = $('.video-container').height();
            var tabH = $('.tabs-cnt').height();
            var footerH = $('.footer').height();
            var chatH = window.screen.height;
            $('.chat-con').css({'height': Math.floor(chatH - viewContainerH - tabH - footerH - 5) + 'px'});
        },

        init: function () {
            // 显示礼物
            $.getJSON('http://192.168.1.78:8001/api/gifts', function (gifts) {
                if (gifts.length > 0) {
                    page.gifts = gifts;

                    var slides = '';
                    for (var i = 0; i < gifts.length; i++) {
                        if (i % 8 === 0) {
                            if (i > 0) {
                                slides += '</ul></div>';
                            }
                            slides += '<div class="swiper-slide " ><ul class="clearfix">';
                        }

                        slides += '<li>'
                            + '<a class="gift-icon" href="javascript:;" data-gid="' + gifts[i]._id + '" data-price="' + gifts[i].price + '">'
                            + '<img src="' + gifts[i].img.icon + '">'
                            + '</a>'
                            + '<p class="gift-name">' + gifts[i].name + '</p>'
                            + '<p class="gift-price">' + gifts[i].price_label + '</p>'
                            + '</li>';

                        if (i === gifts.length - 1) {
                            slides += '</ul></div>';
                        }
                    }

                    $('.gift-list').empty().append(slides);
                    // 绑定礼物
                    var swiperH = new Swiper('.gift-layer-con', {
                        pagination: '.gift-layer-con > .pagination',
                        direction: 'horizontal',
                        paginationClickable: true,
                        spaceBetween: 50
                    });
                } else {
                    console.warn('礼物信息为空');
                }
            });

            // 显示表情
            $.getJSON('http://192.168.1.78:8001/api/emojis', function (emojis) {
                if (emojis.length > 0) {
                    page.emojis = emojis;
                    var slides = '';

                    for (var i = 0; i < emojis.length; i++) {
                        if (i % 17 === 0) {
                            if (i > 0 && i !== emojis.length - 1) {
                                slides += '<li><a class="undo-phiz-icon" href="javascript:;"></a></li></ul></div>';
                            }
                            slides += '<div class="swiper-slide " ><ul class="clearfix">';
                        }

                        slides += ' <li>'
                            + '<a class="phiz-icon" href="javascript:;" data-txt="' + emojis[i].name + '">'
                            + '<img src="' + emojis[i].png + '">'
                            + '</a>'
                            + '</li>';

                        if (i === emojis.length - 1) {
                            slides += '<li><a class="undo-phiz-icon" href="javascript:;"></a></li></ul></div>';
                        }
                    }

                    $('.phiz-list').empty().append(slides);

                    new Swiper('.phiz-layer-con', {
                        pagination: '.phiz-layer-con > .pagination',
                        direction: 'horizontal',
                        paginationClickable: true,
                        spaceBetween: 50
                    });
                } else {
                    console.log('表情信息为空');
                }
            });

            this.userinfo = {
                user_id: $.getUrlParam('user_id'),
                nick_name: $.getUrlParam('nick_name'),
                mobile: $.getUrlParam('mobile'),
                email: $.getUrlParam('email'),
                level: $.getUrlParam('level'),
                avatar: '',
                user_name: $.getUrlParam('user_name'),
                type: '',
                from: 'web'

            };
            this.userLevels = [
                {
                    level: 5,
                    img: "https://i.ssl.pdim.gs/bb3978c2324b499d616270778703d064.png"
                },
                {
                    level: 4,
                    img: "https://i.ssl.pdim.gs/9f68ba2241d7253d46d8b709d31cdcf8.png"
                },
                {
                    level: 3,
                    img: "https://i.ssl.pdim.gs/bde8c896a4bc5f6377423f71a234458e.png"
                },
                {
                    level: 2,
                    img: "https://i.ssl.pdim.gs/118680b2e3c945d9c2a8feb9eed9760f.png"
                },
                {
                    level: 1,
                    img: "https://i.ssl.pdim.gs/66d0d7f80f0b1d36d510c1149d748415.png"
                },];

            w.showGift = function (obj) {
                var arr = obj.content.split('*');
                if (arr.length === 2) {

                    var gift = page.getGift(arr[0]);
                    page.randerGift($.extend(gift, {count: arr[1], fromName: obj.nick_name, user_id: obj.user_id}));

                }

            }
            w.showMessage = function (obj, action) {
                // 判断是否是礼物
                if (obj.type === w.messageType.gift) {
                    var arr = obj.content.split('*');
                    if (arr.length === 2) {
                        var gift = page.getGift(arr[0]);
                        page.randerGift($.extend(gift, {count: arr[1], fromName: obj.nick_name, user_id: obj.user_id}));
                    }
                    return;
                }
                if (typeof(obj.content) !== 'undefined') {
                    if (!page.hideDanmu) {
                        $('.h5-live-danmu').barrager({info: page.randerEmojiContent(obj.content)});
                    }
                }

                var html = '<li class="chat-item">';
                html += '<div class="message">';

                if (obj.level != null && obj.level > 0) {
                    html += '<span class="chat-tag-user-level icon-level-' + obj.level + '"><img src="' + page.getLevel(parseInt(obj.level)).img + '"></span>';
                }

                html += '<span class="chat-user-name">' + obj.nick_name + ' : </span>';
                html += '<span class="chat-content">' + (typeof(obj.content) === 'undefined' ? (action === 'login' ? ' 我进来了' : ' 我离开了') : page.randerEmojiContent(obj.content)) + '</span>';
                html += '</div></li> ';
                $('.msg-list').append(html);
                if ($(".msg-list > li").length > 50) {
                    $(".msg-list > li").slice(0, 25).remove();
                }
                $('.chat-con').scrollTop(10000);
            };
            setInterval(page.timeout, 1000);
        },
        event: function () {
            // 连接聊天服务器
            // room_id, user_id, nick_name, avatar, level, type, from
            w.init(
                $.getUrlParam('room_id'),
                page.userinfo.user_id,
                page.userinfo.nick_name,
                page.userinfo.avatar,
                page.userinfo.level,
                page.userinfo.type,
                page.userinfo.from);


            function stopPropagation(e) {
                if (e.stopPropagation) {
                    e.stopPropagation();
                }
                else
                    e.cancelBubble = true;
            }

            // 发送消息
            $('.btn-cmt-send').click(function () {
                var $input = $('.cmt-input  input');

                // 1:普通消息,2:礼物消息,3:主播消息
                w.sendMessage($input.val(), 1)

                $input.val('');
            });

            // 打开礼物
            $('.cmt-gift').click(function () {
                $('.gift-layer-con').addClass('showGiftLayer');
                $('.footer').removeClass('showPhiz');
            });


            // 打开表情
            $('.cmt-phiz').click(function () {
                $('.footer').addClass('showPhiz');
                console.log(page.randerEmojiContent('[:疑问]还有事吗？'));
            });

            // 点击其他地方隐藏礼物
            $(document).bind('click', function () {
                $('.gift-layer-con').removeClass('showGiftLayer');
                $('.footer').removeClass('showPhiz');
            });

            // 阻止事件冒泡
            $('.gift-layer-con,.cmt-gift,.h5-live-bar,.cmt-phiz,.phiz-list').bind('click', function (e) {
                stopPropagation(e);
            });

            // 绑定送礼物事件
            $('.gift-list').delegate('.gift-icon[data-gid]', 'click', function () {
                console.log($(this));
                var _id = $(this).attr('data-gid');
                var gift = page.getGift(_id);

                var exists = $.grep(page.sendGiftInfo, function (item) {
                    if (item._id === _id) {
                        item.count++;
                        item.time = 12;
                    }
                    return item._id === _id;
                });

                var count = 1;
                if (exists.length === 0) {
                    var fistSend = {
                        _id: _id,
                        count: 1,
                        time: 12
                    };
                    page.sendGiftInfo.push(fistSend);
                } else {
                    count = exists[0].count;
                }

                w.sendMessage(gift._id + '*' + count, w.messageType.gift);

                page.randerGift($.extend(gift, {
                    count: count,
                    fromName: page.userinfo.nick_name,
                    user_id: page.userinfo.user_id
                }));
            });
            //绑定表情事件
            $('.phiz-list').delegate('.phiz-icon[data-txt]', 'click', function () {
                var txt = $(this).attr('data-txt');
                var $input = $('.cmt-input  input');
                $input.val($input.val() + txt);
            });
            $('.phiz-list').delegate('.undo-phiz-icon', 'click', function () {
                $('.cmt-input  input').val('');
            });

            // 绑定tab切换事件
            $('.tabs-list').click(function () {
                var $this = $(this);
                var $type = $this.attr('data-type');

                if (!$this.hasClass('active')) {
                    if ($('.' + $type + '-con').is(':hidden')) {
                        $('.' + $type + '-con').siblings().hide();
                        $('.' + $type + '-con').show();
                    }

                    if ($type === "chat") {
                        $('.footer').show();
                    } else {
                        $('.footer').hide();
                    }
                    $('.tabs-list').removeClass('active');
                    $this.addClass('active');
                }
            });

            // 点击开始观看直播
            $('.btn-play').click(function () {
                $(this).hide();
                $('.h5-live-player-wrapper').addClass('play show');

                // 视频中的直播信息
                $('.play').unbind('click').click(function () {
                    if ($(this).hasClass('show')) {
                        $('.play').removeClass('show');
                    } else {
                        $('.h5-live-player')[0].play();
                        $(this).addClass('show');
                    }
                    setTimeout(function () {
                        $('.play').removeClass('show');
                    }, 5000);
                });

                $('.btn-pause').unbind('click').click(function () {
                    $('.btn-play').show();
                    $('.h5-live-player-wrapper').removeClass('play show');
                });

                $('.btn-danmu').unbind('click').click(function () {
                    if (!$('.h5-live-player-wrapper').hasClass('hide-danmu')) {
                        $('.h5-live-player-wrapper').addClass('hide-danmu')
                        // TODO hide danmu
                        page.hideDanmu = true;
                        $.fn.barrager.removeAll();
                    } else {
                        $('.h5-live-player-wrapper').removeClass('hide-danmu');
                        page.hideDanmu = false;
                    }
                });

            });
        }
    };
    page.init();
    page.event();
    page.ChangeH();


    window.addEventListener("resize", page.changeH, false);

});

